package pers.cj.pdos.controller;


import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.BaseRowModel;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import pers.cj.pdos.controller.base.BaseController;
import pers.cj.pdos.controller.entity.ResponseData;
import pers.cj.pdos.controller.entity.ResponseEntity;
import pers.cj.pdos.controller.entity.ResponseList;
import pers.cj.pdos.entity.*;
import pers.cj.pdos.excel.ExcelHouseIn;
import pers.cj.pdos.excel.ExcelInGoods;
import pers.cj.pdos.service.IHouseInService;
import pers.cj.pdos.task.CleanTempExcelTask;
import pers.cj.pdos.utils.*;
import pers.cj.pdos.vo.*;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author chenj
 * @since 2020-01-14
 */
@Controller
@RequestMapping("/house")
public class HouseInController extends BaseController {

    @Autowired
    IHouseInService houseInService;

    @RequiresPermissions("houseIn:query")
    @RequestMapping("/houseInMain")
    public String houseInMain(){
        return "houseIn/houseInMain";
    }

    @RequiresPermissions("houseIn:query")
    @RequestMapping("/houseIn")
    public String houseIn(){
        return "houseIn/houseIn";
    }


    @RequiresPermissions("houseIn:houseIn")
    @RequestMapping("/houseInNew")
    public String houseInNew(Model model, String houseWaitInId){
        model.addAttribute("houseWaitInId",houseWaitInId);
        return "houseIn/houseInNew";
    }


    @RequiresPermissions("houseIn:query")
    @RequestMapping("/houseInDetail")
    public String houseInDetail(Model model, String id){
        model.addAttribute("id",id);
        return "houseIn/houseInDetail";
    }

    @ResponseBody
    @RequiresPermissions("houseIn:query")
    @RequestMapping("/houseIn/getList")
    public ResponseList getList(int page,
                                int limit,
                                String close,
                                String type,
                                String search,
                                String no,
                                String linkNo,
                                String goodsName,
                                String remark,
                                String unitName,
                                String makeTime1,
                                String makeTime2,
                                String makeUserId,
                                String userId,
                                String date1,
                                String date2,
                                String storeId,
                                String houseId){
        Company company = getCompany();
        UserVo userVo = getLoginUserVo();
        List<HouseInVo> list = houseInService.listVo(company.getId(),
                page,
                limit,
                Utils.genBoolean(close),
                Utils.genInteger(type),
                Utils.genLikeData(search),
                Utils.genLikeData(no),
                Utils.genLikeData(linkNo),
                Utils.genLikeData(goodsName),
                Utils.genLikeData(remark),
                Utils.genLikeData(unitName),
                Utils.genDate(makeTime1),
                Utils.genDate(makeTime2),
                makeUserId,
                PdosUtils.getViewOrderStoreId(userVo,null),
                PdosUtils.getViewOrderUserId(userVo,userId),
                Utils.genDate(date1),
                Utils.genDate(date2),
                storeId,
                houseId);

        long count = houseInService.count(company.getId(),
                Utils.genBoolean(close),
                Utils.genInteger(type),
                Utils.genLikeData(search),
                Utils.genLikeData(no),
                Utils.genLikeData(linkNo),
                Utils.genLikeData(goodsName),
                Utils.genLikeData(remark),
                Utils.genLikeData(unitName),
                Utils.genDate(makeTime1),
                Utils.genDate(makeTime2),
                makeUserId,
                PdosUtils.getViewOrderStoreId(userVo,null),
                PdosUtils.getViewOrderUserId(userVo,userId),
                Utils.genDate(date1),
                Utils.genDate(date2),
                storeId,
                houseId);

        return ResponseList.success(count,list);
    }

    @ResponseBody
    @RequiresPermissions("houseIn:houseIn")
    @RequestMapping("/houseIn/add")
    public ResponseEntity add(@RequestBody HouseInVo houseInVo){
        Company company = getCompany();

        if (Utils.isEmpty(houseInVo.getNo())){
            return ResponseEntity.fail("编号不能为空");
        }

        if (Utils.isEmpty(houseInVo.getHouseId())){
            return ResponseEntity.fail("houseId不能为空");
        }

        if (Utils.isEmpty(houseInVo.getHouseInGoodsVoList()) && Utils.isEmpty(houseInVo.getHouseInPacketVoList())){
            return ResponseEntity.fail("您未选择任何商品");
        }

        if (houseInVo.getDate() == null){
            return ResponseEntity.fail("业务日期不能为空");
        }

        if (houseInService.checkNo(houseInVo.getNo(),company.getId())){
            return ResponseEntity.fail("编号已被使用");
        }

        HouseIn houseIn = DataUtil.genEntityFromVo(HouseIn.class, houseInVo);
        DataUtil.processEntity(company,houseIn);
        houseIn.setClose(false);//正常
        houseIn.setMakeUserId(getLoginUserId());
        houseIn.setMakeTime(houseIn.getTime());

        List<HouseInGoods> houseInGoodsList= new ArrayList<>();
        List<GoodsSn> goodsSnList= new ArrayList<>();
        List<GoodsSnLog> goodsSnLogList= new ArrayList<>();

        Map<String,Object> snInitMap = new HashMap<>();
        snInitMap.put("inDate", new Date());//设置入库日期
        snInitMap.put("status", 1);//设置状态为未出库
        if (!Utils.isEmpty(houseInVo.getHouseInGoodsVoList())) {
            for (HouseInGoodsVo vo : houseInVo.getHouseInGoodsVoList()) {
                HouseInGoods entity = DataUtil.genEntityFromVo(HouseInGoods.class, vo);
                DataUtil.processEntity(company, entity);
                entity.setHouseInId(houseIn.getId());
                houseInGoodsList.add(entity);

                if (!Utils.isEmpty(vo.getGoodsSnList())) {
                    for (GoodsSn goodsSn : vo.getGoodsSnList()) {
                        DataUtil.processEntity(company, goodsSn, snInitMap);
                        goodsSnList.add(goodsSn);

                        GoodsSnLog log = new GoodsSnLog();
                        DataUtil.processEntity(company, log);
                        log.setGoodsId(goodsSn.getGoodsId());
                        log.setSn(goodsSn.getSn());
                        log.setType(4);
                        log.setHouseInGoodsId(entity.getId());
                        goodsSnLogList.add(log);
                    }
                }
            }
        }


        List<HouseInPacket> houseInPacketList= new ArrayList<>();
        List<HouseInPacketGoods> houseInPacketGoodsList= new ArrayList<>();
        if (!Utils.isEmpty(houseInVo.getHouseInPacketVoList())) {
            for (HouseInPacketVo vo : houseInVo.getHouseInPacketVoList()) {
                HouseInPacket entity = DataUtil.genEntityFromVo(HouseInPacket.class, vo);
                DataUtil.processEntity(company, entity);
                entity.setHouseInId(houseIn.getId());
                houseInPacketList.add(entity);


                for (HouseInPacketGoodsVo pgv : vo.getPacketGoodsVoList()) {
                    HouseInPacketGoods pg = DataUtil.genEntityFromVo(HouseInPacketGoods.class, pgv);
                    DataUtil.processEntity(company, pg);
                    pg.setHouseInId(entity.getHouseInId());
                    pg.setHouseInPacketId(entity.getId());
                    houseInPacketGoodsList.add(pg);
                }
            }
        }


        houseInService.insert(houseIn,houseInGoodsList, goodsSnList,goodsSnLogList,houseInPacketList,houseInPacketGoodsList);
        return ResponseEntity.success();
    }


    @ResponseBody
    @RequiresPermissions("houseIn:close")
    @RequestMapping("/houseIn/close")
    public ResponseEntity close(@RequestBody HouseIn houseIn){
        //检查是否已经关闭
        if (houseInService.checkClose(houseIn)){
            return ResponseEntity.fail("该单据已被关闭，不能重复关闭");
        }

        houseInService.close(houseIn);
        return ResponseEntity.success();
    }


    @ResponseBody
    @RequiresPermissions("houseIn:query")
    @RequestMapping("/houseIn/getVoById")
    public ResponseData getVoById(String id) {
        return ResponseData.success(houseInService.getVoById(id));
    }



    @ResponseBody
    @RequiresPermissions("houseIn:query")
    @RequestMapping("/houseIn/listVoByHouseWaitIn")
    public ResponseData listVoByHouseWaitIn(String houseWaitInId) {
        return ResponseData.success(houseInService.listVoByHouseWaitIn(houseWaitInId));
    }

    /**
     * 先更具请求数据
     * @throws IOException
     */
    @ResponseBody
    @RequiresPermissions("houseIn:export")
    @RequestMapping("/houseIn/export")
    public ResponseData export(String close,
                               String type,
                               String search,
                               String no,
                               String linkNo,
                               String goodsName,
                               String remark,
                               String unitName,
                               String makeTime1,
                               String makeTime2,
                               String makeUserId,
                               String userId,
                               String date1,
                               String date2,
                               String storeId,
                               String houseId){
        Company company = getCompany();
        UserVo userVo = getLoginUserVo();
        List<HouseInVo> list = houseInService.listVo(company.getId(),
                null,
                null,
                Utils.genBoolean(close),
                Utils.genInteger(type),
                Utils.genLikeData(search),
                Utils.genLikeData(no),
                Utils.genLikeData(linkNo),
                Utils.genLikeData(goodsName),
                Utils.genLikeData(remark),
                Utils.genLikeData(unitName),
                Utils.genDate(makeTime1),
                Utils.genDate(makeTime2),
                makeUserId,
                PdosUtils.getViewOrderStoreId(userVo,null),
                PdosUtils.getViewOrderUserId(userVo,userId),
                Utils.genDate(date1),
                Utils.genDate(date2),
                storeId,
                houseId);

        String fileName = "入库单列表" + DateUtils.getDate(new Date(), DateUtils.YYYYMMDDHHMMSSSS) + ".xlsx";
        try {
            String path = FileProperUtil.getInstance().getVal("excel.temp");
            OutputStream out = new FileOutputStream(path+fileName);
            ExcelWriter writer = new ExcelWriter(out, ExcelTypeEnum.XLSX,true);
            Sheet sheet1 = new Sheet(1,0, ExcelHouseIn.class);
            sheet1.setSheetName("入库单信息");
            writer.write(genExcelHouseInList(list), sheet1);
            writer.finish();
            out.close();
            CleanTempExcelTask.put(fileName,new Date().getTime());
            return ResponseData.success(fileName);
        } catch (IOException e) {
            return ResponseData.fail("订单列表导出失败");
        }
    }

    private List<ExcelHouseIn> genExcelHouseInList(List<HouseInVo> houseInVoList) {
        List<ExcelHouseIn> list = new ArrayList<>();
        for (HouseInVo vo : houseInVoList){
            ExcelHouseIn excel = new ExcelHouseIn();
            excel.setDate(DateUtils.getDate(vo.getDate(), DateUtils.YYYY_MM_DD));
            excel.setNo(vo.getNo());
            if (vo.getType() == 1){
                excel.setLinkNo(vo.getInGoodsVo().getNo());
                excel.setUnit(vo.getInGoodsVo().getProvider().getName());
                excel.setLinkBusiness("进货");
            } else if (vo.getType() == 2){
                excel.setLinkNo(vo.getRefundVo().getNo());
                excel.setUnit(vo.getRefundVo().getCustom().getName());
                excel.setLinkBusiness("销售退货");
            } else if (vo.getType() == 3){
                excel.setLinkNo(vo.getGoodsTransferVo().getNo());
                excel.setUnit("");
                excel.setLinkBusiness("调拨");
            } else if (vo.getType() == 4){
                excel.setLinkNo(vo.getBorrowInVo().getNo());
                excel.setUnit(vo.getBorrowInVo().getProvider().getName());
                excel.setLinkBusiness("借入");
            } else if (vo.getType() == 5){
                excel.setLinkNo(vo.getBorrowOutBackVo().getNo());
                excel.setUnit(vo.getBorrowOutBackVo().getCustom().getName());
                excel.setLinkBusiness("借出归还");
            }
            excel.setStore(vo.getHouseVo().getStore().getName());
            excel.setHouse(vo.getHouseVo().getName());

            String goods = "";
            BigDecimal number = new BigDecimal("0");
            for (HouseInGoodsVo houseInGoodsVo : vo.getHouseInGoodsVoList()){
                number = number.add(houseInGoodsVo.getNumber());
                goods += houseInGoodsVo.getGoodsVo().getName() + "、";
            }
            excel.setGoods(goods);

            excel.setNumber(PdosUtils.getNumber(number,getBusinessSet()));
            excel.setUser(vo.getUser().getName());
            excel.setMaker(vo.getMakeUser().getName());
            excel.setRemark(vo.getRemark());
            excel.setClose(vo.getClose() ? "是":"否");
            list.add(excel);
        }
        return list;
    }


}
